<template>
  <div class="product-list" style="padding: 0px;">
    <el-card>
      <el-tabs v-model="activeName" @tab-change="handleClick">
        <el-tab-pane label="出售中" name="sell">
          <template #label>
            <span>
              出售中
              <el-tag size="small">{{ productCount.sell }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="已回收" name="lower">
          <template #label>
            <span>
              已回收
              <el-tag size="small">{{ productCount.lower }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="回收站" name="recovery">
          <template #label>
            <span>
              回收站
              <el-tag size="small">{{ productCount.recovery }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="库存紧张" name="stock">
          <template #label>
            <span>
              库存紧张
              <el-tag size="small">{{ productCount.stock }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="已售罄" name="over">
          <template #label>
            <span>
              已售罄
              <el-tag size="small">{{ productCount.over }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
        <!-- <el-form-item label="商品类型">
          <el-select style="width:200px" size="small" @change="onFilterChnage" v-model="searchForm.productType">
            <el-option v-for="(item, index) in productTypes" :key="index" :label="item.name"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品分类">
          <el-select style="width:200px" size="small" @change="onSubmit" v-model="searchForm.categoryId" placeholder="所有分类" filterable clearable>
            <el-option label="全部" value="0"></el-option>
            <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.categoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input size="small" v-model="searchForm.productName" placeholder="请输入商品名称" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="Search" @click="onSubmit">查询</el-button>
          <el-button @click="onReset" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button size="small" icon="Plus" @click="addClick" v-auth="'/product/product/add'" plain>添加产品</el-button>
      <el-button size="small" icon="Bottom" @click="exportClick" v-auth="'/product/product/add'" plain>导出商品</el-button>
      <el-button size="small" icon="Top" @click="importClick" v-auth="'/product/product/add'" plain>导入商品</el-button>
      <el-table size="small" :data="tableData" border style="width: 100%;margin-top:5px;" v-loading="loading" stripe>
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="productName" label="产品" width="400px;">
          <template #default="scope">
            <table>
              <tr>
                <td>
                  <img @click="viewImg(scope.row)" v-if="scope.row.imagePath" :src="scope.row.imagePath" style="width:45px;height:45px;border-radius:5px;" />
                  <!-- <img v-img-url="scope.row.imagePath" alt style="width:45px;height:45px;border-radius:5px;" /> -->
                </td>
                <td>
                  <span style="margin-left:10px;">{{ scope.row.productName }}</span>
                </td>
                <td>
                  <span style="margin-left:10px;color:red;"><sub style="font-size:10px;font-weight:bold;">￥{{ scope.row.productPrice }}</sub></span>
                </td>
              </tr>
            </table>
          </template>
        </el-table-column>
        <el-table-column prop="productType" label="商品类型" width="100" align="center">
          <template #default="scope">
            {{ filterTypeName(scope.row.productType) }}
          </template>
        </el-table-column>
        <el-table-column prop="categoryParentName" label="品种" align="center"></el-table-column>
        <el-table-column prop="categoryName" label="分类" align="center"></el-table-column>
        <el-table-column prop="salesActual" label="实际销量" align="center"></el-table-column>
        <el-table-column prop="productStock" label="库存" align="center"></el-table-column>
        <el-table-column prop="viewTimes" label="点击数" align="center"></el-table-column>
        <el-table-column label="商品属性" align="center">
          <template #default="scope">
            <span v-if="scope.row.isVirtual == 0">实物商品</span>
            <span v-if="scope.row.isVirtual == 1" class="green">虚拟商品</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="150" align="center"></el-table-column>
        <!-- <el-table-column prop="productSort" label="排序"></el-table-column> -->
        <el-table-column prop="productStatus" label="状态" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.productStatus === 10" style="color:green;">正常</span>
            <span v-if="scope.row.productStatus === 20" style="color:red;">已回收</span>
            <span v-if="scope.row.productStatus === 30" style="color:gray;">已放入回收站</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button @click="viewClick(scope.row)" type="text" size="small" v-auth="'/product/product/view'" icon="View">查看</el-button>
            <el-button @click="editClick(scope.row)" type="text" size="small" v-auth="'/product/product/edit'" v-if="scope.row.productStatus === 10" icon="Edit">编辑</el-button>
            <el-button @click="changeStatus(scope.row, 10)" type="text" size="small" v-auth="'/product/product/edit'" v-if="scope.row.productStatus === 20" icon="RefreshLeft" style="color:green">恢复</el-button>
            <el-button @click="changeStatus(scope.row, 20)" type="text" size="small" v-auth="'/product/product/edit'" v-if="scope.row.productStatus === 10" icon="Coffee" style="color:orange">回收</el-button>
            <el-button @click="delClick(scope.row)" type="text" size="small" v-auth="'/product/product/edit'" icon="Delete" style="color:red">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination style="margin-top:10px;float:right;margin-bottom:10px;" @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="totalDataNumber"></el-pagination>
    
    </el-card>

    <el-dialog v-model="productImportShow" title="商品导入" width="30%" :show-close="false" :close-on-click-modal="false">
      <el-upload ref="uploadRef" class="upload-demo" v-model:file-list="fileList" :limit="1" :auto-upload="false">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importCancle">关闭</el-button>
          <el-button type="primary" :loading="importLoading" @click="importSave">导入</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="详情图片" v-model="dialogVisibleImg" width="60%" :before-close="handleClose">
      <img style="margin: 0 auto;" :src="dialogVisibleImgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import PorductApi from '@/api/product.js';
import { defaultPageSize } from '@/utils/table.js'
import Table from './part/spec/many/Table.vue';
export default {
  components: {Table},
  data() {
    return {
      dialogVisibleImg: false,
      dialogVisibleImgUrl: '',
      /*切换菜单*/
      activeName: 'sell',
      /*切换选中值*/
      activeIndex: '0',
      /*是否正在加载*/
      loading: true,
      /*一页多少条*/
      pageSize: 10,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*搜索参数*/
      searchForm: {
        productName: '',
        categoryId: '',
        productType: 1
      },
      productTypes: [
        { name: '普通商品', value: 1 },
        { name: '拼团活动', value: 2 },
        { name: '秒杀活动', value: 3 },
        { name: '预售活动', value: 4 },
        { name: '进口苗活动', value: 5 },
        { name: '特惠活动', value: 6 },
      ],
      /*列表数据*/
      tableData: [],
      /*全部分类*/
      categoryList: [],
      productCount: {},
      productImportShow: false,
      importLoading: false,
      fileList: []
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    viewImg(row) {
      this.dialogVisibleImgUrl = row.imagePath
      this.dialogVisibleImg = true;
    },
    onFilterChnage(e) {
      this.searchForm.productType = e
      this.onSubmit()
    },
    filterTypeName(value) {
      const item = this.productTypes.find(f => f.value === value)
      if (item)
        return item.name
      return ''
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.loading = true;
      self.curPage = val;
      self.getData();
    },

    /*每页多少条*/
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },

    /*切换菜单*/
    handleClick(tab) {
      let self = this;
      self.curPage = 1;
      self.activeName = tab;
      self.getData();
    },

    /*获取列表*/
    getData() {
      let self = this;
      let Params = self.searchForm;
      Params.pageIndex = self.curPage;
      Params.pageSize = self.pageSize;
      Params.type = self.activeName;
      self.loading = true;
      PorductApi.productList(Params, true)
        .then(res => {
          self.loading = false;
          self.tableData = res.data.productList.records;
          self.categoryList = res.data.categoryList;
          self.totalDataNumber = res.data.productList.total;
          self.productCount = res.data.productCount;
        })
        .catch(error => {
          self.loading = false;
        });
    },

    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.getData();
    },
    onReset(){
      this.searchForm.productName = null;
      this.searchForm.categoryId = null;
      this.curPage = 1;
      this.getData();
    },
    /*打开添加*/
    addClick() {
      this.$router.push('/product/product/add');
    },
    // 导出商品
    exportClick() {
      PorductApi.exportProduct()
        .then(res => {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const fdate = new Date()
          const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`
          a.download = perx + '商品列表.xlsx'
          a.click()
          setTimeout(() => {
            a.remove()
          }, 1000)
        })
    },
    importClick() {
      this.productImportShow = true
    },
    importCancle() {
      this.fileList = []
      this.productImportShow = false
    },
    importSave() {
      debugger
      const $this = this
      const files = this.$refs['uploadRef']
      const list = this.fileList
      if (list <= 0) {
        ElMessage.error('请选择文件')
        return
      }
      if (files) {
        const file = list[0].raw
        $this.importLoading = true
        const formData = new FormData()
        formData.append('iFile', file)
        PorductApi.batchImportProduct(formData)
          .then(result => {
            const { code, data, msg } = result
            if (code === 1) {
              ElMessage.success(msg)
            } else {

              ElMessage.error(msg)
            }
            $this.importLoading = false
            $this.productImportShow = false
          }).catch(error => {
            $this.importLoading = false
          })
      }
    },
    /*打开编辑*/
    editClick(row) {
      console.log(row);
      // this.$router.push({
      //   path: '/product/product/edit',
      //   query: {
      //     productId: row.productId,
      //     scene: 'edit'
      //   }
      // });
      let text = this.$router.resolve({
        path: '/product/product/edit',
        query: {
          productId: row.productId,
          scene: 'edit'
        }
      });
      // 打开一个新的页面     
      window.open(text.href, '_blank')
    },
    // 查看
    viewClick(row) {
      console.log(row);
      this.$router.push({
        path: '/product/product/view',
        query: {
          productId: row.productId,
          scene: 'view'
        }
      });
    },

    linkClick: function (val) {
      let self = this;
      let copyText = 'pages/product/detail/detail?productId=' + val;
      self.$copyText(copyText).then(function (e) {
        ElMessage({
          showClose: true,
          message: '复制成功',
          type: 'success'
        });
      }, function (e) {
        ElMessage({
          showClose: true,
          message: '复制失败',
          type: 'error'
        });
      })
    },
    /*打开复制*/
    copyClick(row) {
      this.$router.push({
        path: '/product/product/edit',
        query: {
          productId: row.productId,
          scene: 'copy'
        }
      });
    },
    /*删除*/
    delClick: function (row) {
      let self = this;
      let msg = '';
      if (row.productStatus == 30) {
        msg = '删除后不可恢复，确认删除该记录吗?';
      } else {
        msg = '删除后将移动到回收站，确定删除该记录吗?';
      }
      ElMessageBox.confirm(msg, '提示', {
        type: 'warning'
      })
        .then(() => {
          PorductApi.delProduct({
            productId: row.productId
          }).then(data => {
            ElMessage({
              message: '删除成功',
              type: 'success'
            });
            self.getData();
          });
        });
    },
    /*修改状态*/
    changeStatus(item, value) {

      let self = this;
      let msg = '';
      if (value == 10) {
        msg = '确认要上架该商品吗?';
      } else {
        msg = '确认要下架该商品吗?';
        if (self.activeName == 'recovery') {
          msg = '确认要移动该商品到仓库吗?';
        }
      }
      ElMessageBox.confirm(msg, '提示', {
        type: 'warning'
      })
        .then(() => {
          PorductApi.changeStatus({
            productId: item.productId,
            state: value
          }).then(data => {
            ElMessage({
              message: '操作成功',
              type: 'success'
            });
            self.getData();
          });
        });
    },
  }
};
</script>

<style></style>
